//
//  XS_KCMulu.swift
//  XueDao
//
//  Created by 韩云智 on 2021/1/5.
//

import UIKit
import RxCocoa
import RxSwift
import RxDataSources
import SnapKit

class XS_KCcurriculumHourDtoListM: XS_BaseModel {
    var watchNum = "" // 观看人数
    var isWatch = "" // 是否可以试看 可yes 不可no
    var curriculumHourTitle = "" // 课时标题
    var curriculumHourName = "" // 课时名称
    var duration = "" // 课时时长
    var id = 0 // 课时编号
    var selected = false //是否选中
    var progress : Int32 = 0//下载进度
    var filePath = ""//文件路径
    var isManage = false//是否可以管理删除
    var videoSize = ""
    var isDownloading = 0
    var sts : XS_KCqueryHoursSTS = XS_KCqueryHoursSTS()
}

class XS_KCqueryHoursSTS: XS_BaseModel {
    var vid = "" // 章节类型
    var akScret = "" // 章节类型
    var regionId = "" // 章节类型
    var akId = "" // 章节类型
    var stk = "" // 章节类型
}

class XS_KCqueryHoursM: XS_BaseModel {
    var curriculumHourDtoList: [XS_KCcurriculumHourDtoListM] = [] // 课时集合
    var chapterType = "" // 章节类型
    var chapterName = "" // 章节名称
    var id = 0 // 章节编号
    var isOpen = false
    var num = 0
    var selected = false //是否选中状态
}

class XS_KCMulu: UIView {
    lazy var isBuy = false
    lazy var muluNum = 0
    typealias Section = SectionModel<XS_KCqueryHoursM, XS_KCcurriculumHourDtoListM>
    lazy var disposeBag = DisposeBag()
    lazy var changePS = PublishSubject<Void>()
    lazy var actionPS = PublishSubject<XS_KCcurriculumHourDtoListM>()
    lazy var models: [XS_KCqueryHoursM] = []
    var dataSource: RxTableViewSectionedReloadDataSource<Section>!
    let id: Int
    init(_ id: Int) {
        self.id = id
        super.init(frame: .zero)
        upView()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func upView() {
        
        let table = UITableView(frame: .zero, style: .grouped)
        table.showsVerticalScrollIndicator = false
        table.contentInsetAdjustmentBehavior = .never
        table.bounces = false
        table.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        table.separatorStyle = .none
        table.rowHeight = .scale*68
        table.sectionFooterHeight = 0
        table.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: .screenWidth, height: .scale*8))
        table.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: .screenWidth, height: .scale*8))
        table.register(XS_KCMuluCell.self, forCellReuseIdentifier: "cell")
        table.register(XS_KCMuluHeader.self, forHeaderFooterViewReuseIdentifier: "header")
        addSubview(table)
        var constraint: Constraint!
        table.snp.makeConstraints({
            $0.top.left.right.equalToSuperview()
            constraint = $0.height.equalTo(.scale*68).constraint
            $0.bottom.lessThanOrEqualToSuperview().offset(-.scale*8)
        })
        table.rx.observe(CGSize.self, "contentSize")
            .subscribe(onNext: { size in
                guard let size = size, size != .zero else { return }
                constraint.update(offset: size.height)
            }).disposed(by: self.disposeBag)
        
        let dataSource = RxTableViewSectionedReloadDataSource<Section>(configureCell: { [weak self] ds, tv, ip, it in
            let cell = tv.dequeueReusableCell(withIdentifier: "cell", for: ip) as! XS_KCMuluCell
            let rows = tv.numberOfRows(inSection: ip.section)
            cell.model.onNext((it, rows, ip.row, self?.isBuy ?? false))
            return cell
        })
        self.dataSource = dataSource
        table.rx.setDelegate(self)
            .disposed(by: disposeBag)
        table.rx.modelSelected(XS_KCcurriculumHourDtoListM.self)
            .asDriver()
            .drive(onNext: { [weak self] item in
                self?.actionPS.onNext(item)
            }).disposed(by: disposeBag)
        
        changePS.asDriver(onErrorJustReturn: ())
            .flatMapLatest ({ [weak self] _ in
                let models = self?.models ?? []
                return Driver.just(models.compactMap({ Section(model: $0, items: ($0.chapterType == "first" || $0.isOpen) ? $0.curriculumHourDtoList : []) }))
            }).drive(table.rx.items(dataSource: dataSource))
            .disposed(by: disposeBag)
        reload()
    }
    
    func reload() {
        XS_NetWork.requestJson("/hour/queryHours", parameters: ["id":id])
            .mapModels(type: XS_KCqueryHoursM.self)
            .subscribe(onNext: { [weak self] models, resp in
                guard let `self` = self else { return }
                self.models = models
                self.changePS.onNext(())
            }).disposed(by: disposeBag)
    }
}

extension XS_KCMulu: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            muluNum = 0
        }
        let model = dataSource.sectionModels[section].model
        if model.chapterType == "normal" {
            muluNum += 1
            model.num = muluNum
            return .scale*54
        }
        return 0
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let model = dataSource.sectionModels[section].model
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") as! XS_KCMuluHeader
        header.modelPS.onNext(model)
        header.selectBlock = { [weak self] in
            model.isOpen = !model.isOpen
            self?.changePS.onNext(())
        }
        return header
    }
}

class XS_KCMuluHeader: UITableViewHeaderFooterView {
    lazy var disposeBag = DisposeBag()
    var selectBlock: (()->Void)?
    lazy var modelPS = PublishSubject<XS_KCqueryHoursM>()
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        upView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func upView() {
        let tap = UITapGestureRecognizer()
        addGestureRecognizer(tap)
        tap.rx.event.asDriver()
            .drive(onNext: { [weak self] _ in
                self?.selectBlock?()
            }).disposed(by: disposeBag)
        
        let numLab = UILabel.xsLabel(size: .scale*14, fontName: .medium, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1))
        contentView.addSubview(numLab)
        numLab.snp.makeConstraints({
            $0.centerY.equalToSuperview()
            $0.left.equalTo(.scale*16)
        })
        let nameLab = UILabel.xsLabel(size: .scale*16, fontName: .medium, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1))
        contentView.addSubview(nameLab)
        nameLab.snp.makeConstraints({
            $0.centerY.equalToSuperview()
            $0.left.equalTo(numLab.snp.right).offset(.scale*8)
        })
        let imgV = UIImageView()
        contentView.addSubview(imgV)
        imgV.snp.makeConstraints({
            $0.width.height.equalTo(.scale*12)
            $0.centerY.equalToSuperview()
            $0.right.equalTo(-.scale*16)
        })
        let lab = UILabel.xsLabel(size: .scale*14, fontName: .medium, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1), alignment: .right)
        contentView.addSubview(lab)
        lab.snp.makeConstraints({
            $0.centerY.equalToSuperview()
            $0.right.equalTo(imgV.snp.left).offset(-.scale*8)
        })
        
        modelPS.subscribe(onNext: { item in
            let formatter = NumberFormatter()
            formatter.numberStyle = .spellOut
            let string = formatter.string(from: NSNumber(value: item.num))!
            numLab.text = "第\(string)章"
            nameLab.text = item.chapterName
            lab.text = "共\(item.curriculumHourDtoList.count)讲"
            imgV.image = UIImage(named: item.isOpen ? "icon_12px_更多_1" : "icon_12px_更多_2")
        }).disposed(by: disposeBag)
    }
}

class XS_KCMuluCell: XS_BaseTCell {
    lazy var model = PublishSubject<(XS_KCcurriculumHourDtoListM, Int, Int, Bool)>()
    
    override func getLineEdgeInsets() -> UIEdgeInsets {
        UIEdgeInsets(top: 0, left: .scale*28, bottom: 0, right: -.scale*28)
    }
    
    override func upView() {
        super.upView()
        loadLine()
        let shapeLayer = CAShapeLayer()
        shapeLayer.frame = CGRect(x: .scale*16, y: 0, width: .scale*343, height: .scale*68)
        shapeLayer.fillColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        layer.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        layer.mask = shapeLayer
        
        let imgV = UIImageView()
        contentView.addSubview(imgV)
        imgV.snp.makeConstraints { maker in
            maker.width.height.equalTo(.scale*24)
            maker.left.equalTo(.scale*28)
            maker.centerY.equalToSuperview()
        }
        
        let tLab = UILabel.xsLabel(size: .scale*14, fontName: .regular, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1))
        contentView.addSubview(tLab)
        tLab.snp.makeConstraints { maker in
            maker.left.equalTo(.scale*64)
            maker.right.lessThanOrEqualToSuperview().offset(-.scale*29)
            maker.top.equalTo(.scale*12)
        }
        
        let cLab = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1))
        contentView.addSubview(cLab)
        cLab.snp.makeConstraints { maker in
            maker.left.equalTo(.scale*64)
            maker.top.equalTo(.scale*40)
        }
        
        let layerView = UIView()
        layerView.frame = CGRect(x: 16, y: 0, width: 41, height: 18) * .scale
        layerView.layer.cornerRadius = 4 * .scale
        layerView.alpha = 1
        // fillCode
        let bgLayer1 = CALayer()
        bgLayer1.frame = layerView.bounds
        bgLayer1.backgroundColor = UIColor(red: 0.83, green: 0.95, blue: 0.92, alpha: 1.00).cgColor
        layerView.layer.addSublayer(bgLayer1)
        contentView.addSubview(layerView)
        let label = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1), alignment: .center, text: "可试看")
        layerView.addSubview(label)
        label.snp.makeConstraints {
            $0.center.equalToSuperview()
        }
        
        model.subscribe(onNext: { [weak self] (item, rows, row, isBuy) in
            let corners: UIRectCorner
            switch (rows, row) {
            case (1, 0): corners = .allCorners
            case (2..., 0): corners = [.topLeft, .topRight]
            case (2..., rows-1): corners = [.bottomLeft, .bottomRight]
            default: corners = []
            }
            layerView.isHidden = !(item.isWatch == "yes")
            imgV.image = UIImage(named: (item.isWatch == "yes" || isBuy) ? "icon_24px_播放" : "icon_24px_播放_1")
            tLab.text = item.curriculumHourTitle
            cLab.text = "\(item.duration) | \(item.watchNum)人学过"
            self?.line.isHidden = corners.contains(.bottomLeft)
            shapeLayer.path = UIBezierPath(roundedRect: shapeLayer.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: .scale*15, height: .scale*15)).cgPath
        }).disposed(by: disposeBag)
    }

}
